package com.gaoyu.regexparser;

import com.gaoyu.regexparser.Expression.Asterisk;
import com.gaoyu.regexparser.Expression.Constant;
import com.gaoyu.regexparser.Expression.Expression;
import com.gaoyu.regexparser.Expression.Plus;
import com.gaoyu.regexparser.Expression.QuestionMark;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gaoyu on 2017/5/15.
 */

public class ExpressionFactory {

    private List<Expression> expressionList = new ArrayList<>();

    private ExpressionFactory() {

        expressionList.add(new QuestionMark());
        expressionList.add(new Asterisk());
        expressionList.add(new Plus());
        expressionList.add(new Constant());
    }

    public static class FactoryHolder {
        public static ExpressionFactory mInstance = new ExpressionFactory();
    }

    public static ExpressionFactory getInstance() {
        return FactoryHolder.mInstance;
    }

    public Expression createExpression(char c) {

        Expression expression = null;

        for (Expression exp : expressionList) {

            if (exp.interpret(c)) {
                Class clazz = null;
                try {
                    clazz = Class.forName(exp.getClass().getName());
                    try {
                        expression = (Expression) clazz.newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

                break;
            }
        }
        return expression;
    }
}
